<?php
/**
 * UserController.php
 *
 * @copyright  2023 beikeshop.com - All Rights Reserved
 * @link       https://beikeshop.com
 * @author     TL <mengwb@guangda.work>
 * @created    2023-05-10 14:44:54
 * @modified   2023-05-10 14:44:54
 */

namespace Beike\Seller\Http\Controllers;

use Beike\Seller\Http\Requests\UserRequest;
use Beike\Seller\Models\SellerUser;
use Beike\Seller\Repositories\PermissionRepo;
use Beike\Seller\Repositories\UserRepo;
use Illuminate\Http\Request;

class UserController extends Controller
{
    /**
     * 获取账号列表
     *
     * @return mixed
     */
    public function index()
    {
        $data = [
            'users' => UserRepo::getUsers(),
        ];

        return view('seller::pages.users.index', $data);
    }

    public function create()
    {
        $permissionRepo = (new PermissionRepo());
        $data           = [
            'permissions'   => $permissionRepo->getPermissions(),
            'user'          => new SellerUser(),
        ];

        return view('seller::pages.users.edit', $data);
    }

    /**
     * @param int $id
     * @return mixed
     */
    public function edit(int $id)
    {
        $user           = UserRepo::find($id);
        $permissionRepo = (new PermissionRepo())->setUser($user);
        $data           = [
            'permissions'   => $permissionRepo->getPermissions(),
            'user'          => $user,
        ];

        return view('seller::pages.users.edit', $data);
    }

    /**
     * 创建账号
     *
     * @param UserRequest $request
     * @return array
     */
    public function store(UserRequest $request)
    {
        $user = UserRepo::createUser($request->toArray());

        return redirect(seller_route('users.index'))->with('success', trans('common.created_success'));
    }

    /**
     * 更新账号
     *
     * @param UserRequest $request
     * @param int         $id
     * @return array
     */
    public function update(UserRequest $request, int $id)
    {
        $user = UserRepo::updateUser($id, $request->toArray());

        return redirect(seller_route('users.index'))->with('success', trans('common.updated_success'));
    }

    /**
     * @param Request $request
     * @param int     $id
     * @return array
     * @throws \Exception
     */
    public function destroy(Request $request, int $id)
    {
        UserRepo::deleteUser($id);

        return json_success(trans('common.deleted_success'));
    }
}
